#include "selectcpp_c.h"
#ifdef SELECT_C_C6_CPP
#define _CRT_SECURE_NO_WARNINGS

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory.h>
#include <thread>
#include <iostream>
#include <climits>

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <windows.h>

void sendFile(FILE *fp, SOCKET sockfd){
	char buf[101];
	while (fgets(buf, 100, fp) != nullptr){
		send(sockfd, buf, strlen(buf), 0);
	}
	printf("send finished\n");
	shutdown(sockfd, SD_SEND);
}

void str_cli(FILE* fp, SOCKET sockfd){
	std::thread t(sendFile, fp, sockfd);

	int stdineof = 0;
	char buf[101];
	int n;

	while ((n = recv(sockfd, buf, 100, 0)) > 0){
		buf[n] = 0;
		printf("send back : %s\n", buf);
	}

	t.join();
}

int main(int argc, char *argv[]){
	WSAData wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	SOCKET sockfd;
	sockaddr_in servaddr;

	if (argc != 2){
		printf("arg count error");
		exit(0);
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	memset(&servaddr, 0, sizeof(sockaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(12000);
	inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	if (connect(sockfd, reinterpret_cast<sockaddr*>(&servaddr), sizeof(servaddr)) == INVALID_SOCKET)
	{
		printf("connect error code %d\n", WSAGetLastError());
	}
	FILE *fp = fopen("send.txt", "r");
	str_cli(fp, sockfd);
	fclose(fp);
	return 0;
}

#endif